﻿using Admin2024.Domain.Entity.System;
using Admin2024.Domain.IDomainService.System.IUserService;
using Admin2024.Domain.Interface;
using Admin2024.Domain.ObjValue;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Admin2024.Domain.DomainService.System.UserService
{
    public class UserRoleManagementService : IUserRoleManagementService
    {
        private readonly IRepository<AppUser> UserRep = null!;

        private readonly IRepository<AppRole> RoleRep=null!;

        private readonly IRepository<AppUserRole> UserRoleRep = null!;


        public UserRoleManagementService(IRepository<AppUser> UserRep , IRepository<AppRole> RoleRep, IRepository<AppUserRole> UserRoleRep) { 
            
            this.UserRep = UserRep;
            this.RoleRep = RoleRep;
            this.UserRoleRep = UserRoleRep;
        }
        public async Task<DomainResult<string>> AssignRoleToUser(Guid appUserId, Guid appRoleId)
        {
            var User = await UserRep.GetByIdAsync(appUserId);
            var Role = await RoleRep.GetByIdAsync(appRoleId);

            //1 查找是否存在
            if (User != null && Role != null)
            {

                var appUserRole = new AppUserRole { AppUserId = User.Id, AppRoleId = Role.Id };
                await UserRoleRep.CreateAsync(appUserRole);
                return DomainResult<string>.Success("分配角色成功");

            }

            return DomainResult<string>.Error("分配角色失败");
        }

        public async Task<DomainResult<string>> RemoveRoleFromUser(Guid appUserId, Guid appRoleId)
        {
            var User = await UserRep.GetByIdAsync(appUserId);
            var Role = await RoleRep.GetByIdAsync(appRoleId);

            var appUserRoleId = Guid.NewGuid();
            if (User != null && Role != null)
            {
                var userRole = UserRoleRep.Table.Where(x => x.AppUserId == appUserId && x.AppRoleId == appRoleId);
                foreach (var item in userRole)
                {
                    appUserRoleId = item.Id;
                }

                await UserRoleRep.DeleteAsync(appUserRoleId);

                return DomainResult<string>.Success("删除角色成功");
            }

            return DomainResult<string>.Error("删除角色失败");


        }
    }
}
